db = require "../db"
# Bot = require "../bot"
monk = require "monk"
Puppet = require "wechaty-puppet"
console.log Puppet.types
MessageType= Puppet.types.Message
Wechaty = require "wechaty"
{ FileBox } = require "file-box"
# console.log Bot

module.exports =
  doSend: (sendid) ->
    bot = global["bot"]
    model = await db.SEND.findOne monk.id sendid
    for roomid in model.rooms
      try
        room = await bot.Room.load roomid


        r = await db.ROOM.findOne id: room.id
        return unless r.expires > new Date()
        return unless room

        for message in model.messages
          console.log message
          try
            if message.type is MessageType.Text
              await room.say message.payload

            if message.type is MessageType.MiniProgram
              msg = new bot.MiniProgram message.payload
              await room.say msg

            if message.type is MessageType.Image
              console.log 'sendimage : ' + message.path
              filebox = FileBox.fromFile message.path
              await room.say filebox

            if message.type is MessageType.Url
              urllink = new bot.UrlLink message.payload
              await room.say urllink
          catch err
            console.log err
      catch e
        console.log e
